//
//  LeslieImageCache.m
//  AsyncUIImageView
//
//  Created by Leslie.Fang on 14-8-11.
//  Copyright (c) 2014年 Enway. All rights reserved.
//

#import "VideoImageCache.h"
#import <CommonCrypto/CommonDigest.h>

@implementation VideoImageCache

+(VideoImageCache*)sharedCache {
    static VideoImageCache *imageCache = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        imageCache = [[self alloc] init];
    });
    
    return imageCache;
}

-(id)init{
    if (self == [super init]) {
        ioQueue = dispatch_queue_create("com.yueshichina.VideoImageCache", DISPATCH_QUEUE_SERIAL);
        
        memCache = [[NSCache alloc] init];
        memCache.name = @"image_cache";
        
        fileManager = [NSFileManager defaultManager];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        cacheDir = [paths objectAtIndex:0];
    }
    
    return self;
}

-(void)cacheImageToMemory:(UIImage*)image forKey:(NSString*)key{
    if (image) {
        [memCache setObject:image forKey:key];
    }
}

-(UIImage*)getImageFromMemoryForkey:(NSString*)key{
    return [memCache objectForKey:key];
}

-(void)cacheImageToFile:(UIImage*)image forKey:(NSString*)key ofType:(NSString*)imageType{
    if (!image || !key ||!imageType) {
        return;
    }
    
    dispatch_async(ioQueue, ^{
       NSString *filename = [self.class md5:key];
        NSString *filepath = [cacheDir stringByAppendingPathComponent:filename];
        
        NSLog(@"cacheImageToFile filepath = %@",filepath);
        NSData *data = nil;
        
        if ([imageType isEqualToString:@"jpg"]) {
            data = UIImageJPEGRepresentation(image, 1.0);
        }else{
            data = UIImagePNGRepresentation(image);
        }
        
        if (data) {
            [data writeToFile:filepath atomically:YES];
        }
    });
}

-(UIImage*)getImageFromFileForKey:(NSString*)key{
    if (!key) {
        return nil;
    }
    
    NSString *filename = [self.class md5:key];
    NSString *filepath = [cacheDir stringByAppendingPathComponent:filename];
     NSLog(@"getImageFromFileForKey filepath = %@",filepath);
    if ([fileManager fileExistsAtPath:filepath]) {
        UIImage *image = [UIImage imageWithContentsOfFile:filepath];
        return image;
    }
    
    return nil;
}

//md5 encode
+(NSString *) md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (unsigned int)strlen(cStr), digest );
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02X", digest[i]];
    
    return output;
}

@end
